import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";
import { setRouterTitle } from "@/utils";

Vue.use(VueRouter);

const router = new VueRouter({
  routes,
  mode: "history",
});

router.beforeEach((to, from, next) => {
  const stateNow = store.getters["loginUser/stateNow"];

  if (to.meta.requireAuth) {
    if (stateNow === "loading") {
      // 等待验证
      next({ name: "Loading", query: { redirect: to.fullPath } });
    } else if (stateNow === "logined") {
      // 已登录
      next();
    } else {
      // 未登录
      next({ name: "Login" });
    }
  } else {
    next();
  }
});

router.afterEach((to) => {
  const title = to.meta.title;
  setRouterTitle(title);
});

export default router;
